<?php
header('Content-Type: application/json');

try {
    // 读取 POST 数据
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['content']) || !isset($data['created_at'])) {
        throw new Exception('数据格式错误');
    }

    // 读取现有留言
    $messagesFile = '../admin/data/messages.json';
    if (!file_exists($messagesFile)) {
        file_put_contents($messagesFile, json_encode(['messages' => [], 'next_id' => 1]));
    }
    
    $messages = json_decode(file_get_contents($messagesFile), true);
    if (!isset($messages['next_id'])) {
        $messages['next_id'] = 1;
    }
    
    // 添加新留言，默认状态为待审核
    $messages['messages'][] = [
        'id' => $messages['next_id']++,
        'content' => $data['content'],
        'province' => $data['province'],
        'city' => $data['city'],
        'created_at' => $data['created_at'],
        'status' => 'pending'
    ];

    // 保存回文件（保持最新的100条留言）
    $messages['messages'] = array_slice($messages['messages'], -100);
    
    if (file_put_contents($messagesFile, json_encode($messages, JSON_PRETTY_PRINT))) {
        echo json_encode(['success' => true]);
    } else {
        throw new Exception('保存失败');
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?> 